package com.crawler.waf.exceptions.handlers;

import com.crawler.waf.exceptions.messages.ErrorMessage;
import com.crawler.waf.exceptions.providers.ErrorMessageProvider;
import com.google.common.base.Throwables;

import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * Waf默认的简单异常类的定义
 *
 */
public class WafDefaultExceptionHandler extends AbstractWafExceptionHandler {

	private ErrorMessageProvider provider = super.getProvider();
	private String errorCode = "WAF/INTERNAL_SERVER_ERROR";
	
	public WafDefaultExceptionHandler(HttpStatus status) {
		super(status);
	}
	
	public WafDefaultExceptionHandler(HttpStatus status,String errorCode) {
		super(status);
		this.errorCode = errorCode;
	}
	
	public WafDefaultExceptionHandler(Class<?> exceptionClass) {
		super(exceptionClass);
	}
	
	public WafDefaultExceptionHandler(Class<?> exceptionClass,String errorCode) {
		super(exceptionClass);
		this.errorCode = errorCode;
	}

	public WafDefaultExceptionHandler(Class<?> exceptionClass, HttpStatus status,String errorCode) {
		super(exceptionClass, status);
		this.errorCode = errorCode;
	}


	@Override
	public Object createBody(Exception ex, HttpServletRequest req) {
		ErrorMessage em = provider.handleMessage();
		em.setCode(errorCode);
		provider.handleServerInfo(em, req);
		if(ex!=null&&!"".equals(ex.getMessage())){
			em.setMessage(ex.getMessage());
		}else{
			em.setMessage(super.getStatus().getReasonPhrase());
		}
		em.setStackTrace(Throwables.getStackTraceAsString(ex));

		return em;
	}

}
